<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Card, Form, Input, Button, message, Spin, InputNumber, Upload } from 'ant-design-vue';
import { UploadOutlined, SaveOutlined, LeftOutlined } from '@ant-design/icons-vue';
import { getAppVoById, updateApp, updateAppByAdmin } from '@/api/appController';
import { useUserStore } from '@/stores/user';
import type { FormInstance } from 'ant-design-vue';

// 路由参数
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
// 直接使用字符串形式的ID，不进行parseInt转换
const appId = ref<string>(route.params.id as string);

// 表单和数据
const formRef = ref<FormInstance>();
const loading = ref(true);
const submitting = ref(false);
const formData = ref({
  id: undefined as string | undefined,
  appName: '',
  cover: '',
  priority: 0
});

// 上传文件列表
const fileList = ref<any[]>([]);

// 是否管理员
const isAdmin = computed(() => {
  return userStore.loginUser?.userRole === 'admin';
});

// 是否可编辑优先级（仅管理员可编辑）
const canEditPriority = computed(() => {
  return isAdmin.value;
});

// 获取应用详情
const fetchAppInfo = async () => {
  loading.value = true;
  try {
    const res = await getAppVoById({ id: appId.value });
    if (res.data?.code === 0 && res.data?.data) {
      const appInfo = res.data.data;
      
      // 检查当前用户是否是应用的所有者或管理员
      if (appInfo.userId !== userStore.loginUser.id && !isAdmin.value) {
        message.error('您没有权限编辑此应用');
        router.push('/');
        return;
      }
      
      // 设置表单数据
      formData.value = {
        id: appInfo.id,
        appName: appInfo.appName || '',
        cover: appInfo.cover || '',
        priority: appInfo.priority || 0
      };
      
      // 设置上传文件列表
      if (appInfo.cover) {
        fileList.value = [{
          uid: '-1',
          name: 'cover.jpg',
          status: 'done',
          url: appInfo.cover
        }];
      }
      
      // 设置页面标题
      document.title = `编辑 ${appInfo.appName} - AI Generator`;
    }
  } catch (error) {
    console.error('获取应用详情失败', error);
    message.error('获取应用详情失败');
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate();
    
    submitting.value = true;
    const submitData = {
      id: appId.value,
      appName: formData.value.appName
    };
    
    // 根据用户角色选择不同的API
    let res;
    if (isAdmin.value) {
      res = await updateAppByAdmin({
        id: appId.value,
        appName: formData.value.appName,
        cover: formData.value.cover,
        priority: formData.value.priority
      });
    } else {
      res = await updateApp(submitData);
    }
    
    if (res.data?.code === 0 && res.data?.data) {
      message.success('保存成功');
      router.push('/');
    } else {
      message.error(res.data?.message || '保存失败');
    }
  } catch (error) {
    console.error('保存失败:', error);
    message.error('表单验证失败或保存失败');
  } finally {
    submitting.value = false;
  }
};

// 处理上传前的钩子
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('您只能上传图片文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!');
  }
  return isImage && isLt2M;
};

// 自定义上传（这里需要替换为实际的上传逻辑）
const customUpload = ({ file, onSuccess, onError }: any) => {
  // 示例：实现将文件上传到服务器的逻辑，这里使用模拟的逻辑
  const uploadData = new FormData();
  uploadData.append('file', file);
  
  // 实际项目中，这里应该调用上传API
  setTimeout(() => {
    // 模拟上传成功
    const imageUrl = URL.createObjectURL(file);
    formData.value.cover = imageUrl;
    onSuccess("Upload success", { url: imageUrl });
  }, 1000);
};

// 返回
const goBack = () => {
  router.go(-1);
};

// 组件挂载后获取应用详情
onMounted(() => {
  fetchAppInfo();
});
</script>

<template>
  <div class="app-edit-view">
    <Card :bordered="false" class="edit-card">
      <template #title>
        <div class="header-content">
          <Button type="text" @click="goBack" class="back-button">
            <LeftOutlined />
          </Button>
          <span>编辑应用</span>
        </div>
      </template>
      
      <Spin :spinning="loading">
        <Form 
          ref="formRef" 
          :model="formData" 
          layout="vertical"
          class="edit-form"
        >
          <!-- 应用ID -->
          <Form.Item name="id" style="display: none">
            <Input v-model:value="formData.id" />
          </Form.Item>
          
          <!-- 应用名称 -->
          <Form.Item 
            label="应用名称" 
            name="appName"
            :rules="[{ required: true, message: '请输入应用名称' }]"
          >
            <Input v-model:value="formData.appName" placeholder="请输入应用名称" />
          </Form.Item>
          
          <!-- 应用封面（仅管理员可见） -->
          <Form.Item 
            label="应用封面" 
            name="cover"
            v-if="isAdmin"
          >
            <Upload
              v-model:fileList="fileList"
              name="cover"
              list-type="picture-card"
              :customRequest="customUpload"
              :before-upload="beforeUpload"
              :max-count="1"
            >
              <div v-if="fileList.length < 1">
                <UploadOutlined />
                <div style="margin-top: 8px">上传</div>
              </div>
            </Upload>
          </Form.Item>
          
          <!-- 优先级（仅管理员可见） -->
          <Form.Item 
            label="优先级" 
            name="priority"
            v-if="canEditPriority"
            extra="设置为99可作为精选应用展示"
          >
            <InputNumber v-model:value="formData.priority" :min="0" :max="99" />
          </Form.Item>
          
          <!-- 提交按钮 -->
          <Form.Item>
            <Button 
              type="primary" 
              :loading="submitting" 
              @click="handleSubmit"
              class="submit-button"
            >
              <template #icon><SaveOutlined /></template>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Spin>
    </Card>
  </div>
</template>

<style scoped>
.app-edit-view {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.edit-card {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 8px;
}

.edit-form {
  max-width: 600px;
  margin: 0 auto;
}

.submit-button {
  min-width: 100px;
}

.ant-upload-list-picture-card-container {
  width: 200px;
  height: 200px;
}
</style> 